<template>

  <div class="host">
    <div class="host_search">
      <div class="components-input-demo-size">
        <span>
          主机类别:
          <a-select default-value="lucy" style="width: 120px" @change="handleChange">
            <a-select-option value="jack">
              Jack
            </a-select-option>
            <a-select-option value="lucy">
              Lucy
            </a-select-option>
          </a-select>
        </span>
        <span>
          主机别名:
          <a-input placeholder="default size"/>
        </span>
        <span>
          连接地址:
          <a-input placeholder="default size"/>
        </span>
        <span>
          <a-button type="primary" icon="undo">
            刷新
          </a-button>
        </span>
      </div>
    </div>
    <div class="host_add" style="margin-top: 20px">
      <span>
        <a-button type="primary" icon="plus" @click="showModal">
          新建
        </a-button>
      </span>
      <span>
        <a-button type="primary" icon="underline" @click="showExcelModal">
          批量导入
        </a-button>
      </span>
    </div>
    <div>
      <a-modal v-model="visible" title="批量导入" @ok="handleExcelOk">
        <template slot="footer">
          <a-button key="back" @click="handleUploadExcelCancel">
            取消
          </a-button>
          <a-button
            type="primary"
            :disabled="excel_fileList.length === 0"
            :loading="excel_uploading"
            style="margin-top: 16px"
            @click="handleExcelUpload"
          >
            {{ excel_uploading ? 'Uploading' : 'Start Upload' }}
          </a-button>
        </template>

        <div>
          <a-alert type="info"
                   message="导入或输入的密码仅作首次验证使用，并不会存储密码。"
                   banner
                   closable
          />
          <br/>
          <a-form :form="upload_excel_form">

            <a-form-item
              :label-col="formItemLayout.labelCol"
              :wrapper-col="formItemLayout.wrapperCol"
              label="模板下载"
              help="请下载使用该模板填充数据后导入"
            >
              <a href="../../static/file/主机导入模板.xlsx" download="主机导入模板">主机导入模板.xlsx</a>
            </a-form-item>

            <a-form-item
              :label-col="formItemLayout.labelCol"
              :wrapper-col="formItemLayout.wrapperCol"
              label="默认密码"
              help="如果Excel中密码为空则使用该密码"
            >
              <a-input
                v-model="default_password"
                placeholder="请输入默认主机密码"
              />
            </a-form-item>

            <a-form-item
              :label-col="formItemLayout.labelCol"
              :wrapper-col="formItemLayout.wrapperCol"
              label="导入数据"
            >

              <div class="clearfix">
                <a-upload :file-list="excel_fileList" :remove="handleExcelRemove" :before-upload="beforeExcelUpload"
                          v-decorator="[
                    'host_excel',
                    { rules: [{ required: true, message: '请上传文件' }] },
                  ]">
                  <a-button>
                    <a-icon type="upload"/>
                    Select File
                  </a-button>
                </a-upload>
              </div>
            </a-form-item>
          </a-form>
        </div>

      </a-modal>
    </div>

    <div>
      <a-modal v-model="visible" title="新建主机" @ok="handleOk" width="800px">
        <a-form-model
          ref="ruleForm"
          :model="add_host_form.form"
          :rules="add_host_form.rules"
          :label-col="add_host_form.labelCol"
          :wrapper-col="add_host_form.wrapperCol"
        >

          <a-form-model-item label="选择主机类别" prop="category">
            <a-select v-model="add_host_form.form.category" placeholder="请选择主机类别">
              <a-select-option :value="host_category_value.id" v-for="(host_category_value,host_category_index) in host_category_data" :key="host_category_index">
                {{host_category_value.name}}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item ref="hostname" label="输入主机名" prop="hostname">
            <a-input
              v-model="add_host_form.form.hostname"
              @blur="
          () => {
            $refs.hostname.onFieldBlur();
          }
        "
            />
          </a-form-model-item>
          <a-form-model-item ref="name" label="输入连接信息" prop="name">
            <a-row>
              <a-col :span="8">
                <a-input addon-before="用户名" v-model="add_host_form.form.username"/>
              </a-col>
              <a-col :span="8">
                <a-input addon-before="@" v-model="add_host_form.form.ip_addr"/>
              </a-col>
              <a-col :span="8">
                <a-input addon-before="端口号" v-model="add_host_form.form.port"/>
              </a-col>
            </a-row>
          </a-form-model-item>
          <a-form-model-item ref="password" label="输入连接密码" prop="password">
            <a-input
              v-model="add_host_form.form.password"
              @blur="
          () => {
            $refs.password.onFieldBlur();
          }
        "
            />
          </a-form-model-item>
          <a-form-model-item label="描述" prop="desc">
            <a-input v-model="add_host_form.form.desc" type="textarea"/>
          </a-form-model-item>
<!--          <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">-->
<!--            <a-button type="primary" @click="onSubmit">-->
<!--              Create-->
<!--            </a-button>-->
<!--            <a-button style="margin-left: 10px;" @click="resetForm">-->
<!--              Reset-->
<!--            </a-button>-->
<!--          </a-form-model-item>-->
        </a-form-model>

      </a-modal>
    </div>
    <div class="table">
      <a-table :columns="columns" :data-source="host_data" rowKey="id">
        <a slot="action" slot-scope="text" href="javascript:;">
          <a-button type="link" size="small">编辑 |</a-button>
          <a-button type="link" size="small">删除 |</a-button>
          <a-button type="link" size="small">console</a-button>
        </a>
      </a-table>

    </div>

  </div>

</template>

<script>

const columns = [
  {title: 'id', dataIndex: 'id', key: 'name'},
  {title: '类别', dataIndex: 'category_name', key: 'category_name'},
  {title: '主机名称', dataIndex: 'hostname', key: 'hostname'},
  {title: '连接地址', dataIndex: 'ip_addr', key: 'ip_addr'},
  {title: '端口号', dataIndex: 'port', key: 'port'},
  {title: '描述', dataIndex: 'desc', key: 'desc'},
  {title: 'Action', dataIndex: '', key: 'x', scopedSlots: {customRender: 'action'}},
];

// const data = [
//   {
//     id: 1,
//     name: 'John Brown',
//     age: 32,
//     address: 'New York No. 1 Lake Park',
//     description: 'My name is John Brown, I am 32 years old, living in New York No. 1 Lake Park.',
//   },
//   {
//     id: 2,
//     name: 'Jim Green',
//     age: 42,
//     address: 'London No. 1 Lake Park',
//     description: 'My name is Jim Green, I am 42 years old, living in London No. 1 Lake Park.',
//   },
//   {
//     id: 3,
//     name: 'Joe Black',
//     age: 32,
//     address: 'Sidney No. 1 Lake Park',
//     description: 'My name is Joe Black, I am 32 years old, living in Sidney No. 1 Lake Park.',
//   },
// ];

const formItemLayout = {
  labelCol: {span: 8},
  wrapperCol: {span: 12},
};


export default {
  name: "Host",
  data() {
    return {
      // excel
      excel_fileList: [],
      excel_uploading: false,

      upload_excel_form: this.$form.createForm(this, {name: 'coordinated'}),

      default_password: '', // 上传的Excel数据默认使用的密码

      // 模态对话框相关属性
      loading: false,
      excel_model_visible: false, // excel弹框显示或者隐藏

      host_data: [],
      host_category_data: [], //主机类别数据
      columns,
      visible: false,
      excel_visible: false, //批量导入弹框显示和隐藏控制

      add_host_form: {
        labelCol: {span: 4},
        wrapperCol: {span: 14},
        other: '',
        form: {
          hostname: '',
          category: '',
          username: '',
          ip_addr: '',
          port: 22,
          password: '',
          desc: '',
        },
        rules: {
          hostname: [
            {required: true, message: 'Please input hostname', trigger: 'blur'},
            {min: 1, max: 100, message: 'Length should be 3 to 5', trigger: 'blur'},
          ],
          username: [
            {required: true, message: 'Please input hostname', trigger: 'blur'},
            {min: 1, max: 100, message: 'Length should be 3 to 5', trigger: 'blur'},
          ],
          ip_addr: [
            {required: true, message: 'Please input hostname', trigger: 'blur'},
            {min: 1, max: 100, message: 'Length should be 3 to 5', trigger: 'blur'},
          ],
          port: [
            {required: true, message: 'Please input hostname', trigger: 'blur'},
            {min: 1, max: 100, message: 'Length should be 3 to 5', trigger: 'blur'},
          ],
          password: [
            {required: true, message: 'Please input hostname', trigger: 'blur'},
            {min: 1, max: 100, message: 'Length should be 3 to 5', trigger: 'blur'},
          ],
        },
      }


    }
  },
  created() {
    this.get_host_data();
    this.get_host_category_data();
  },

  methods: {

    showExcelModal() {
      this.excel_visible = true;
    },
    handleExcelOk(e) {
      console.log(e);
      this.excel_visible = false;
    },

    showModal() {
      this.visible = true;
    },
    // 点击提交按钮进行数据校验和保存
    handleOk(e) {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          // 前端校验之后的事情
          // alert('submit!');
          // 发送请求携带主机数据到后台进行主机添加
          console.log('添加主机数据>>>', this.add_host_form.form)

          let token = sessionStorage.token || localStorage.token;
          this.$axios.post(`${this.$settings.HOST}/host/list/`, this.add_host_form.form, {
            headers: {
              'Authorization': `jwt ${token}`
          }
          }).then((res)=>{
            // this.host_category_data = res.data;
            this.host_data.push(res.data);
          }).catch((error)=>{
            this.$message.error('请求参数有误！！')
          })

        } else {
          console.log('error submit!!');
          return false;
        }
      });

      console.log(e);
      this.visible = false;
    },

    handleChange(value) {
      this.$refs.ruleForm.resetFields();
      console.log(`selected ${value}`);
    },
    //获取主机类别数据
    get_host_category_data(){
      let token = sessionStorage.token || localStorage.token;
      this.$axios.get(`${this.$settings.HOST}/host/categorys/`, {
          headers: {
            'Authorization': `jwt ${token}`
          }
      }).then((res)=>{
        this.host_category_data = res.data;
      })
    },
    // 获取主机数据
    get_host_data() {
      let token = sessionStorage.token || localStorage.token;
      this.$axios.get(`${this.$settings.HOST}/host/list/`, {
        headers: {
          'Authorization': `jwt ${token}`
        }
      }).then((res) => {
        console.log(res);
        this.host_data = res.data;

      }).catch((error) => {

      })

    },

  }

}
</script>

<style scoped>
.components-input-demo-size .ant-input {
  width: 200px;
  margin: 0 8px 8px 0;
}
</style>
